import hashlib
import requests
from django.core.mail import send_mail
from django.http import JsonResponse
from django.shortcuts import render
from django.template import loader

from bookmanagement.settings import EMAIL_HOST_USER


def hash_str(source):
    return hashlib.new('sha512', source.encode('utf-8')).hexdigest()


def send_email_activate(email, s_id, u_token):
    subject = '云云图书管理系统'
    message = 'http://127.0.0.1:8000/book/register/'
    from_email = EMAIL_HOST_USER
    recipient_list = [email, ]
    data = {
        'username': s_id,
        'active_url': f'http://127.0.0.1:8000/book/activate?u_token={u_token}'
    }
    html_message = loader.get_template('email_active.html').render(data)
    send_mail(subject=subject, html_message=html_message, message='', from_email=from_email,
              recipient_list=recipient_list)


def send_email_fgemail(email, id, u_token):
    subject = '云云图书管理系统'
    from_email = EMAIL_HOST_USER
    recipient_list = [email, ]
    data = {
        'username': id,
        'active_url': f'http://127.0.0.1:8000/book/get_pwd?u_token={u_token}'
    }
    html_message = loader.get_template('email_fg_pwd.html').render(data)
    send_mail(subject=subject, message='', html_message=html_message, from_email=from_email,
              recipient_list=recipient_list)


def pc_icon(url, name):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.39',
        'Cookie': 'll="118099"; bid=jo0k8qn2Hws; douban-fav-remind=1; gr_user_id=b2a993d3-a516-4c0c-9821-607e91303c7b; gr_cs1_74b5f4d1-38a0-4516-8b8b-6687a6dbc28d=user_id%3A0; ap_v=0,6.0; viewed="35763835"; trdipcktrffcext=1'
    }
    data = {
        'q': name
    }
    url = url
    response = requests.get(url=url, headers=headers, params=data)
    print(response.text)
    if len(response.text)<20 :
        return 1
    print(response.json()[0]['pic'])
    return response.json()[0]['pic']
